<template>
	<view class="goods-list">
		<view class="goods-list-container">
			<Search @search="onSearch" @switch-mode="onSwitchShowMode"></Search>
			<Sort @sort="onSort" ref="sort"></Sort>
			<ProductList :list="goodsList" :showMode="showMode"></ProductList>
		</view>
	</view>
</template>

<script>
	import { productList as productListApi } from '@/api/goods'
	import Search from './components/Search'
	import Sort from './components/Sort'
	import ProductList from './components/ProductList'
	export default {
		components: {
			Search,
			Sort,
			ProductList
		},
		data() {
			return {
				params: {
					// 一级分类id
					cid: 0,
					// 二级分类id
					sid: 0,
					// 搜索关键词
					keyword: '',
					// 价格排序
					priceOrder: '',
					// 按销量排序
					salesOrder: '',
					// 是否新品
					news: '',
					page: 1,
					limit: 20,
				},
				goodsList: [],
				showMode: '',
				noMore: false
			}
		},
		onLoad (options) {
			this.params.sid = options.sid
			this.$refs.sort.menuList[0].text = options.sname
			this.getProductList()
		},
		onReachBottom () {
			this.getProductList()
		},
		methods: {
			onSearch (keywords) {
				this.params.keyword = keywords
				this.params.page = 1
				this.noMore = false
				this.getProductList()
			},
			onSwitchShowMode (modeName) {
				this.showMode = modeName
			},
			onSort (sortParams) {
				this.params = {...this.params, ...sortParams}
				this.params.page = 1
				this.noMore = false
				this.getProductList()
			},
			async getProductList () {
				if (this.noMore) {
					return false
				}
			  const { status, data, msg } = await productListApi(this.params)
			  if (status === this.API_STATUS_CODE.SUCCESS) {
				  if (this.params.page > 1) {
					  this.goodsList = [...this.goodsList, ...data]
					  
					  if (data.length === 0) {
						  this.noMore = true
					  }
				  } else {
					  this.goodsList = data
				  }
				  
				  if (data.length) {
					  this.params.page++
				  }
			  } else {
			    uni.showToast({
			      icon: 'none',
			      title: msg,
			      duration: 3000
			    })
			  }
			}
		}
	}
</script>

<style lang="scss" scoped>
</style>
